import JSEncrypt from 'jsencrypt'
import moment from 'moment'
import { ElMessageBox } from 'element-plus'
import { CodeToText } from 'element-china-area-data'
import { getPermissions, getDicts } from './auth'


const encryptor = new JSEncrypt()
const pubKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5XJUTiPgEpK5BP2f5OQeNpdkI
Lyfcsn5QRZVNw8WTgrGEt+1zWFHzpIerB345IyTJ8wOivyFQ8ujlowP52bpUaWVT
Cdf3EbUdVxRWchpUcrNMkWXnoTRnjytLIBirlHD8/7RMifXUCQFlktPLWH2/c61P
d59CNSx+OL3EhtMJzwIDAQAB
-----END PUBLIC KEY-----`
encryptor.setPublicKey(pubKey)

/**
 * @description 生成UUID
 */
 export function $genUUID() {
  let value: number = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    value += performance.now()
  }
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (value + Math.random() * 16) % 16 | 0
    value = Math.floor(value / 16)
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
  return uuid
}

/**
 * @description 动态URL
 * @returns 
 */
export function $dynamicUrl(): string {
  return location.origin + '/api'
}

/**
 * @description 加密
 * @param content 内容 
 * @returns 
 */
export function $encrypt(content: string): string {
  return encryptor.encrypt(content) as string
}

/**
 * @description 判断权限
 * @param { String } value 权限
 */
 export function $hasPermission(value: string) {
  const permissions = getPermissions() || []

  if (value.indexOf('&') !== -1) {
    const vaules = value.split('&')
    return vaules.every((item) => permissions.includes(item))
  } 
  if (value.indexOf('|') !== -1) {
    const vaules = value.split('|')
    return vaules.some((item) => permissions.includes(item))
  } 
  return permissions.includes(value)
}

/**
 * @description 确认框
 * @param { String } message 消息内容
 * @param { export function } callback 回调
 */
export function $confirmMsg(message: string, callback?: Function) {
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    buttonSize: 'default',
    callback(action: string) {
      if (action === 'confirm' && callback) {
        callback()
      }
    }
  })
}

/**
 * @description 格式化时间
 * @param { String } value 时间值
 * @param { String } formatter 格式化形式，默认<yyyy-MM-dd>
 */
export function $moment(value: string | number, formatter?: string) {
  if (!value) return ''
  if (typeof value === 'string' && /^\d+$/.test(value)) {
    value = Number(value)
  }
  formatter = formatter || 'YYYY-MM-DD'
  return moment(value).format(formatter)
}

/**
 * @description 获取指定类型的字典
 * @param { String } type 字典类型
 */
export function $listDict(type: string) {
  const dicts = getDicts() || []
  return dicts[type] || []
}

/**
 * @description 获取指定类型及值的字典标签
 * @param { String } type  字典类型
 * @param { String } value 字典值
 * @param { String } defaultLabel 默认值
 */
export function $getDictLabel(type: string, value: string, defaultLabel?: string) {
  const dicts = $listDict(type)
  for (const key of Object.keys(dicts)) {
    if (key == value) return dicts[key]
  }
  return defaultLabel || ''
}

interface TreeOption {
  id: string
  pid: string
  children: string
}
/**
 * @description 转换树形数据
 * @param { Array } data 原始数据
 * @param { Object } options 树形数据属性
 */
export function $convertTree(data: Array<any>, options?: TreeOption) {
  const option = options || { id: 'id', pid: 'parentId', children: 'children' }
  if(JSON.stringify(data).indexOf(option.children) !== -1) {
    return data
  }

  // 找出父级
  const roots = data.filter((item) => data.findIndex((v) => v[option.id] === item[option.pid]) === -1)

  // 递归子级函数
  const fn = function (id: string) {
    const temp = []
    for (const child of data) {
      if (child[option.pid] === id) {
        child[option.children] = fn(child[option.id])
        temp.push(child)
      }
    }
    return temp
  }

  // 查找父级的子级
  for (const root of roots) {
    root[option.children] = fn(root.id)
  }
  
  return roots
}

/**
 * @description 转换时间单位
 * @param { String } value 时间（秒）
 */
export function $convertTimeUnit(value: string | number) {
  if (!value) return ''
  if (typeof value === 'string' && /^\d+$/.test(value)) {
    value = Number(value)
  }
  let seconds: number = value as number
  let minutes: number = 0
  let hours: number = 0
  let days: number = 0
  if (seconds > 60) {
    minutes = parseInt(String(seconds / 60))
    seconds = parseInt(String(seconds % 60))
  }
  if (minutes > 60) {
    hours = parseInt(String(minutes / 60))
    minutes = parseInt(String(minutes % 60))
  }
  if (hours > 24) {
    days = parseInt(String(hours / 24))
    hours = parseInt(String(hours % 24))
  }

  let result: string = ''
  if (days > 0) {
    result += days + '天'
  }
  if (hours > 0) {
    result += hours + '时'
  }
  if (minutes > 0) {
    result += minutes + '分'
  }
  if (seconds > 0) {
    result += seconds + '秒'
  }
  return result
}

/**
 * @description 地区编码转换为地址
 * @param { String } code 地区编码
 */
 export function $areaCodeToText(code: string) {
  return CodeToText(code)
}


import { uploadFile, downloadFile } from 'src/api/file/index'
import noAvatar from 'src/assets/no_avatar.png?url'

/**
 * @description 上传文件
 * @param { FormData } params 上传文件
 * @returns 
 */
 export async function $upload(params: FormData) {
  if(!params || params.getAll.length == 0) {
    return []
  }
  const { data } = await uploadFile(params)
  return data
}

/**
 * @description 预览文件
 * @param id 
 * @returns 
 */
export async function $preview(id: string) {
  if(!id) {
    return noAvatar
  }
  const blob: any = await downloadFile(id)
  return blob ? URL.createObjectURL(blob) : noAvatar
}

/**
 * @description 获取计量单位
 * @returns 
 */
export function $listPerUnit(): Array<any> {
  const perUnits = localStorage.getItem('PerUnitKey') || '[]'
  return JSON.parse(perUnits)
}

/**
 * @description 获取计量单位
 * @returns 
 */
 export function $getPerUnit(id: string): string {
  const perUnits: Array<any> = $listPerUnit()
  const perUnit = perUnits.find(item => item.id == id)
  return perUnit ? `${ perUnit.code }-${ perUnit.name }` : ''
}
